package com.example.demospringsecurity.security.config;

import com.example.demospringsecurity.filter.JwtAuthenticationTokenFilter;
import com.example.demospringsecurity.security.UserDetailsServiceImpl;
import com.example.demospringsecurity.test.CodeValidProvider;
import com.example.demospringsecurity.test.MyPasswordEncoder;
import com.example.demospringsecurity.test.MyProviderTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.jws.Oneway;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    AuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    AccessDeniedHandler accessDeniedHandler;

    @Autowired
    AuthenticationSuccessHandler successHandler;

    @Autowired
    AuthenticationFailureHandler failureHandler;

    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Autowired
    MyPasswordEncoder myPasswordEncoder;

    @Autowired
    private MyProviderTest authProvider;

    @Autowired
    private CodeValidProvider codeValidProvider;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //configure方法会覆盖父类的configure方法，如果没有重写这个方法，默认走父类的DaoAuthenticationProvider

        //注册自定义认证
        //注册了两个认证provider，只有当前面的AuthenticationProvider认证失败时才会调用后面的AuthenticationProvider
        auth.authenticationProvider(authProvider);
        auth.authenticationProvider(codeValidProvider);
//        auth.authenticationProvider(authProvider);

        //指定userDetailsService
        auth.userDetailsService(userDetailsService);
    }

//    @Bean
//    MyProviderTest myAuthenticationProvider() {
//        MyProviderTest myAuthenticationProvider = new MyProviderTest();
//        myAuthenticationProvider.setPasswordEncoder(passwordEncoder());
//        myAuthenticationProvider.setUserDetailsService(new UserDetailsServiceImpl());
//        return myAuthenticationProvider;
//    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // anonymous()允许匿名访问，表示匿名用户（未认证的用户）有权限访问这个资源。
                .antMatchers("/user/login").permitAll()
                .antMatchers("/hello").hasAuthority("system:test:list")
                //permitAll 表示所有用户（无论是否认证）都有权限访问这个资源。
//                .antMatchers("/hello").permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();

//        http.formLogin(formLoginConfigurer ->
//                formLoginConfigurer.loginProcessingUrl("/user/login")
//                        .usernameParameter("userName")
//                        .passwordParameter("password")
//                        .permitAll());

        //把token校验过滤器添加到过滤器链中,放在UsernamePasswordAuthenticationFilter这个过滤器前面
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
//        http.addFilter(jwtAuthenticationTokenFilter);

        //配置异常处理器
        http.exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);

        //由于我们的资源都会收到SpringSecurity的保护，所以想要跨域访问还要让SpringSecurity运行跨域访问。
        http.cors();

//        http.formLogin()
//                .loginProcessingUrl("/user/login")
//                .passwordParameter("password")
//                .usernameParameter("userName")
////                配置认证成功处理器
//                .successHandler(successHandler)
////                配置认证失败处理器
//                .failureHandler(failureHandler)
//                .and()
//                .logout()
//                .logoutSuccessHandler(new LogoutSuccessHandler() {
//                    @Override
//                    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
//                        System.out.println("退出成功");
//                    }
//                });

    }

    /**
     * 这一步的配置是必不可少的，否则SpringBoot会自动配置一个AuthenticationManager,覆盖掉内存中的用户
     * @return 认证管理对象
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}